<?php
/*
 *  Maniter: A webbased business managment tool.
 *  Copyright (C) 2007  Dimitri Michaux <dimitri.michaux@gmail.com>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * purchaseorder.class.php, Maniter
 * 
 * Manages all the things needed for a purchaseorder: adding, removeing
 * purchases, keeping a footertext, keeping the date and exporting to
 * pdf.
 *
 * @author Dimitri Michaux
 * @version 0.1
 * @package maniter_classes
 */

require_once( 'purchaselist.class.php' );
require_once( 'pdfpurchase.class.php' );
require_once( _PATH_TO_JIBA.'dynamictext.class.php' );
require_once( _PATH_TO_JIBA.'db.class.php' );

class PurchaseOrder extends PurchaseList {
  
  /**
    * The footer text
    *
    * @var DynamicText
    */
  private $_footerText;
  
  /**
    * The advance payment (if any)
    *
    * @var float
    */
  private $_advance;
	
  /**
  * Get a purchaseorder
  *
  * @return   PurchaseOrder|PurchaseOffer
  * @access   public
  */
  public static function &getPurchaseOrder( $id )
  {
    $db = DB::get();  //it appears like on some servers the database should be initialized before
                      //using mysql_real_escape_string, I don't know why this is
    $id = mysql_real_escape_string( $id );
    $res = $db->getRows( 'purchase_orders', "id='$id'" );
    
    $order = new PurchaseOrder( $res[0]['id'] );
    $order->getTimestamp()->setMysqlTimestamp( $res[0]['date'], true );
    $order->setDispId( $res[0]['dispid'] );
    $order->setFooterText( $res[0]['footer'] );
    $order->setAdvance( $res[0]['advance'] );
    
    $res[0]['finished'] ? $order->setFinished() : $order->unSetFinished();
    $res[0]['printed'] ? $order->setPrinted() : '';
    
    $order = PurchaseList::_getPurchases( $order );
    $order = PurchaseList::_getClientInfo( $order );
    
    return $order;
  }
	
  /**
    * Get purchaseorders out of the database.
    *
    * @param	int	$offset		start from
    * @param	int	$limit		limit results to
    * @return	PurchaseOrder[]
    * @access	public
    */
  public function &getPurchaseOrders( $offset=0, $limit=0 ){
    $res = DB::get()->getRows( 'purchase_orders', null, 'dispid', false, $limit, $offset );
    $num = count( $res );
    $orders = array();
    
    for( $i=0 ; $i<$num ; $i++ )
    {
    
    
      $orders[$i] = new PurchaseOrder( $res[$i]['id'] );
      $orders[$i]->getTimestamp()->setMysqlTimestamp( $res[$i]['date'] );
      $orders[$i]->setDispId( $res[$i]['dispid'] );
      $orders[$i]->setFooterText( $res[$i]['footer'] );
      $orders[$i]->setAdvance( $res[$i]['advance'] );
      
      $res[$i]['finished'] ? $orders[$i]->setFinished() : $orders[$i]->unSetFinished();
      $res[$i]['printed'] ? $orders[$i]->setPrinted() : '';
      
      $orders[$i] = PurchaseList::_getPurchases( $orders[$i] );
      $orders[$i] = PurchaseList::_getClientInfo( $orders[$i] );
    }
    
    return $orders;
  }
	
  /**
    * Constructor: initializes variables and objects
    * + creates a database entry for this purchaseorder.
    */
  public function __construct( $id='' ) {
    //initialize variables + create an id
    parent::__construct();
    
    $db = DB::get();
    
    $this->_advance = 0;
    
    $this->_footerText = new DynamicText();
    $this->_footerText->setText( $db->getItem('var_blob','value',"name='ordertext'") );

    //if a valid id has been given, give if to this order
    if( strlen($id)==32 )
            $this->_id = $id;
    else	//create a new id
            $this->_dispId = $this->_incGetOrderId();
  }
	
	/**
	 * Call the parent function + add $_dispId to the array
	 *
	 * @return string
	 */
	public function __sleep() {
		return array_merge( parent::__sleep(), array('_dispId','_footerText') );
	}
	
	public function setAdvance( $advance ){
		if( is_numeric($advance) )
			$this->_advance = round( $advance, 2 );
	}
	
	public function getAdvance(){
		return $this->_advance;
	}
	
	/**
	 * Set the footer text
	 *
	 * @param string $str
	 */
	public function setFooterText( $str ){
		if( is_string($str) )
			$this->_footerText->setText($str);
	}
	
	/**
	 * Returns the unparsed footer
	 *
	 * @return string
	 */
	public function getFooter(){
		return $this->_footerText->getText();
	}
	
	public function parseFooter( $nl2br=true ){
		$this->_footerText->setArgument( 'nr', $this->getDispId() );
		$this->_footerText->setArgument( 'expire', $this->getDueDate() );
		
		return $this->_footerText->parseText( $nl2br );
	}
	
	public function getTotal(){
		return parent::getTotal() - $this->_advance;
	}
	
	/**
	 * This function is only here to compatability with older versions
	 * that don't have the _footerText variable.
	 * 
	 */
	public function __wakeup(){
		global $_DB;
		
		if( !is_a($this->_footerText,'DynamicText') ){
			$this->_footerText = new DynamicText();
			$this->_footerText->setText( $_DB->getItem('var_blob','value',"name='ordertext'") );
		}
	}
	
	/**
	 * Generates a pdf for this purchase order.
	 * 
	 * Make sure you don't output anything else before
	 * or after you call this function!
	 *
	 */
	public function pdf(){
		$pdf = new PdfPurchase();
		
		$pdf->setPurchases( $this->_purchases );
		$pdf->setClientInfo( $this->_clientInfo );
		$pdf->setDate( $this->getTimestamp()->show() );
		$pdf->setDueDate( $this->getDueDate() );
		$pdf->setFootText( $this->parseFooter(false) );
		$pdf->setNumber( $this->_dispId );
		$pdf->setVatPerVat( $this->getVatPerVat(true) );
		$pdf->setSubtotal( $this->printSubtotal() );
		$pdf->setTotal( $this->printTotal() );
		
		if( $this->_advance != 0 )
			$pdf->setAdvance( number_format($this->_advance, 2,',',' ') );

		$pdf->Output();
	}
	
  public static function save( $order ){
    //saves purchases
    PurchaseList::save( $order );
    
    $data = array(  'id' => $order->_id,
                    'date' => $order->getTimestamp()->getMysqlTimestamp(),
                    'printed' => $order->printed() ? 1 : 0,
                    'finished' => $order->_finished ? 1 : 0,
                    'dispid' => $order->_dispId,
                    'advance' => $order->_advance,
                    'footer' => $order->_footerText->getText() );
  
    DB::get()->save( 'purchase_orders', $data, true );
  }
	
	/**
	 * Gets the order id out of the database,
	 * increment it and save it again
	 *
	 * @return int
	 */
	private function _incGetOrderId(){
		$id = DB::get()->getItem( 'var_blob', 'value', "name='orderid'" );
		$id++;
		DB::get()->update( 'var_blob', array('value'=>$id), "name='orderid'" );
		
		return $id;
	}
}

?>